<template>
  <Modal v-model:visible="visible" centered :afterClose="afterClose" :width="750" :title="props.edit ? '编辑项目' : '新建项目'">
    <div class="ModalBox">
      <div class="newProject">
        <div class="headBox">
          <div class="inputBox">
            <a-input class="inputA" @change="projectNameChange" :maxlength="25" v-model:value="formState.projectName"
              placeholder="请输入项目名称" />
            <div v-show="errorMessage" class="errorMessage">项目名称不能为空</div>
          </div>
        </div>
        <div class="infoBox">
          <div class="head">
            基本信息
          </div>
          <div class="basicInform">
            <a-form :colon="false" ref="formRef" :rules="rulesRef" :model="formState">
              <a-form-item label="项目管理员" name="adminList" :labelCol="{ span: 3 }" required labelAlign="left">
                <a-select id="adminList" v-model:value="formState.adminList" :allowClear="true" mode="multiple"
                  :field-names="{ label: 'realname', value: 'id', options: 'options' }" :options="adminOptions"
                  style="width: 100%" placeholder="请选择项目管理员" @change="adminChange">
                  <template #suffixIcon>
                    <StarOutlined />
                  </template>
                </a-select>
              </a-form-item>

              <a-form-item label="所在地区" name="location2" :labelCol="{ span: 3 }" labelAlign="left" required>
                <!-- <a-input style="width: 100%;" placeholder="123" />
                <div class="regionSelect">

                </div> -->
                <JAreaLinkage v-model:value="location2" name="JAreaLinkage" :showArea="false" @stateVal="stateVal">
                </JAreaLinkage>
              </a-form-item>

              <a-row>
                <a-col :span="12">
                  <a-form-item label="客户名称" :labelCol="{ span: 6 }" labelAlign="left">
                    <a-input style="width: 100%;" v-model:value="formState.customerName" placeholder="请输入客户名称" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="客户类型" :labelCol="{ span: 6, offset: 1 }" labelAlign="left">
                    <a-select v-model:value="formState.customerType" :options="customerTypeOptions">
                      <template #placeholder>
                        <span style="color:#c6c6c6">请选择客户类型</span>
                      </template>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item label="项目成员" name="" :labelCol="{ span: 3 }" labelAlign="left">
                <a-select id="memberList" v-model:value="formState.memberList" :allowClear="true" mode="multiple"
                  style="width: 100%" placeholder="请选择项目成员" @deselect="deselect"
                  :field-names="{ label: 'realname', value: 'id', options: 'options' }" :options="adminOptions">
                  <template #suffixIcon>
                    <StarOutlined />
                  </template>
                </a-select>
              </a-form-item>

              <a-row>
                <a-col :span="12">
                  <a-form-item label="项目周期" name="projectTime" :labelCol="{ span: 6, }" labelAlign="left" required>
                    <a-range-picker format="YYYY-MM-DD" v-model:value="projectTime" @change="projectTimeChange" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="项目状态" name="state" :labelCol="{ span: 6, offset: 1 }" labelAlign="left" required>
                    <a-select v-model:value="formState.state" :options="projectState">
                      <template #placeholder>
                        <span style="color:#c6c6c6">请选择项目状态</span>
                      </template>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <div class="addItInform">附加信息</div>
              <a-row>
                <a-col :span="12">
                  <a-form-item label="项目地址" :labelCol="{ span: 6, }" labelAlign="left">

                    <div class="mapLocalBox">
                      <div class="inpBox" @click="dsMap(true)">
                        <a-input v-model:value="form.address" ref="inputRef"></a-input>
                      </div>
                      <div v-show="displayMap" class="MapBox" @click="() => { inputRef.value.focus(); }">
                        <div class="mapSelectBox">
                          <a-select v-model:value="keywords" show-search :default-active-first-option="false"
                            :show-arrow="false" :filter-option="false" :not-found-content="null" @search="remoteMethod"
                            @change="">
                            <template #suffixIcon>
                              <SearchOutlined />
                            </template>

                            <a-select-option v-for="item in options" @click="currentSelect(item)" :value="item.id">{{
                              item.name }}</a-select-option>
                          </a-select>
                        </div>
                        <div id="container"></div>
                        <div class="Mapbut">
                          <a-button type="primary" @click="dsMap(false)">确定</a-button>
                        </div>
                      </div>
                    </div>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="项目预算" :labelCol="{ span: 6, offset: 1 }" labelAlign="left">
                    <a-select v-model:value="formState.budget" :options="budgetOptins" style="width: 100%">
                      <template #placeholder>
                        <span style="color:#c6c6c6">请选择项目预算</span>
                      </template>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-form-item label="项目需求" name="demandContent" :labelCol="{ span: 3 }" labelAlign="left">
                <a-textarea :rows="4" v-model:value="formState.demandContent" placeholder="请输入项目需求" show-count
                  :maxlength="300" />
              </a-form-item>
              <a-form-item label="其他信息" :labelCol="{ span: 3 }" labelAlign="left">
                <a-textarea :rows="4" v-model:value="formState.otherInfo" placeholder="请输入其他信息" show-count
                  :maxlength="300" />
              </a-form-item>
            </a-form>
          </div>
        </div>
        <div class="davidLine"></div>
        <div class="footer">
          <a-button class="resetBox" @click="reset">重置</a-button>
          <a-button class="greatProjectBox" @click="greatProject">{{ props.edit ? '保存项目' : '创建项目' }}</a-button>
        </div>
      </div>
    </div>
  </Modal>
</template>
<script lang="ts" setup>
import { Modal } from 'ant-design-vue';
import { ref, defineProps, watch, defineEmits, reactive, onMounted } from 'vue';
import { StarOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { JAreaLinkage } from '/@/components/Form';
import { UserList, add, queryById, editAPi } from './data.api'
import { Form } from 'ant-design-vue';
import dayjs, { Dayjs } from 'dayjs';
import AMapLoader from "@amap/amap-jsapi-loader";
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  edit: {
    type: Boolean,
  },
  queryId: {
    type: String,
    default: ''
  }
});
const visible = ref<boolean>(false);
let location2 = ref()
let projectTime = ref()
let formRef = ref()
let errorMessage = ref(false)
let displayMap = ref<boolean>(false) // 是否显示地图
let map = null;  // 地图实例
let marker = null; // 标记点
let geoCoder = null// 地址逆解析
let AutoComplete = ref()  // 搜索提示
let keywords = ref()  // 搜索关键字
let inputRef = ref()
// 搜索节流阀
let loading = ref(false)
// 搜索提示信息
let options = ref([])

let form = reactive({
  lng: '',
  lat: '',
  address: '',
  adcode: '',
})
const customerTypeOptions = ref([
  {
    label: '个人',
    value: '0',
  },
  {
    label: '企业',
    value: '1',
  },
  {
    label: '政府单位',
    value: '2',
  },
])
const projectState = ref([
  {
    label: '进行中',
    value: '0',
  },
  {
    label: '暂存',
    value: '1',
  },
  {
    label: '已完结',
    value: '2',
  },
])
const budgetOptins = ref([
  {
    label: '10万元以下',
    value: '0',
  },
  {
    label: '10-15万元',
    value: '1',
  },
  {
    label: '50-100万元',
    value: '2',
  },
  {
    label: '100-500万元',
    value: '3',
  },
  {
    label: '500-1000万元',
    value: '4',
  },
  {
    label: '1000万元以上',
    value: '5',
  },
])
const useForm = Form.useForm;
const emit = defineEmits();

window._AMapSecurityConfig = {
  securityJsCode: 'f151338307a532a145225cbd9c1c714b',
}

watch(
  () => props.open,
  (newVal) => {
    visible.value = newVal;

    AMapLoader.load({
      key: "59c61f064c552f2ace25ff0c1d6465a7",
      version: "2.0",
      plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
    }).then((AMap) => {
      map = new AMap.Map("container", {
        // 设置地图容器id
        // viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        // center: [116.397428, 39.90923], // 初始化地图中心点位置
      });


      geoCoder = new AMap.Geocoder({
        city: "010", //城市设为北京，默认：“全国”
        radius: 1000, //范围，默认：500
      });

      AutoComplete = new AMap.AutoComplete({ city: "全国" });

      map.on('click', (e) => {
        form.lng = e.lnglat.getLng();
        form.lat = e.lnglat.getLat();
        // console.log(e.lnglat.getLng(), e.lnglat.getLat())
        console.log(e)
        removeMarker()
        setMapMarker()
      })

    }).catch((e) => {
      console.log(e);
    });
  }
)

function dsMap(type: boolean) {
  displayMap.value = type
}

function setMapMarker() {
  // 自动适应显示想显示的范围区域
  map.setFitView();
  marker = new AMap.Marker({
    map: map,
    position: [form.lng, form.lat],
  });
  toGeoCoder()
  map.setFitView();
  map.add(marker);
}

function removeMarker() {
  if (marker) {
    map.remove(marker);
  }
}

// 逆解析地址
function toGeoCoder() {
  let lnglat = [form.lng, form.lat];
  // let lnglat = [114.086838, 22.537209];
  console.log(lnglat, 'lnglat')
  geoCoder.getAddress(lnglat, (status, result) => {
    console.log(status, result, 'result')
    if (status === "complete" && result.regeocode) {
      form.address = result.regeocode.formattedAddress;
    }
  });
  console.log(form, 'form')
}
let timer = null;
// 搜索
function remoteMethod(query) {
  console.log(query);
  if (query !== "") {
    if (timer) {
      clearTimeout(timer); // 清除之前的定时器
    }
    loading.value = true;
    timer = setTimeout(() => {
      loading.value = false;
      console.log('定时器触发')
      AutoComplete.search(query, (status, result) => {
        options.value = result.tips;
        console.log(options.value, 'options.value')
      });
    }, 1000);
  } else {
    console.log('清空了opt');
    options.value = [];
  }
}

// 选中提示
function currentSelect(val) {
  console.log(val, 'currentSelect');
  // 清空时不执行后面代码
  if (!val) {
    return;
  }

  form.lng = val.location.lng
  form.lat = val.location.lat
  form.address = val.district + val.address + val.name
  form.adcode = val.adcode

  // 清除点
  removeMarker();
  // 标记点
  setMapMarker();
}



watch(
  () => props.edit,
  (newVal) => {
    if (newVal) {
      getInfo()
    }
  }
)

let formState = reactive({
  adminList: [],
  // provinceCode: location.value ? location.value[0] : '',
  // cityCode: location.value ? location.value[1] : '',
  provinceCode: '',
  cityCode: '',
  customerName: '',
  customerType: null,
  memberList: [],
  startDate: '',
  endDate: '',
  state: null,
  budget: null,
  demandContent: '',
  otherInfo: '',
  projectName: '',
  location: ''
})

const dateFormat = 'YYYY/MM/DD';

async function getInfo() {
  const res = await queryById({ id: props.queryId })
  formState.projectName = res.projectName
  formState.adminList = res.adminList.split(',')
  location2.value = [res.provinceCode, res.cityCode]
  formState.customerName = res.customerName
  formState.customerType = res.customerType
  formState.memberList = res.memberList.split(',')
  formState.state = res.state
  formState.budget = res.budget
  formState.demandContent = res.demandContent
  formState.otherInfo = res.otherInfo
  formState.location = res.location
  form.lng = res.longitude
  form.lat = res.latitude

  formState.startDate = res.startDate
  formState.endDate = res.endDate

  projectTime.value = [
    dayjs(res.startDate, dateFormat),
    dayjs(res.endDate, dateFormat),
  ]

  let lnglat = [res.longitude, res.latitude];
  // let lnglat = [114.086838, 22.537209];

  geoCoder.getAddress(lnglat, (status, result) => {
    console.log(status, result, 'result')
    if (status === "complete" && result.regeocode) {
      form.address = result.regeocode.formattedAddress;
    }
  });
  // const a = new Date('2023-10-18')
  // const b = new Date('2023-10-30')
  // projectTime.value = [convertDateToCustomObject(a), convertDateToCustomObject(b)]
  // console.log(projectTime.value)
}

const rulesRef = reactive({
  adminList: [
    {
      required: true,
      message: '请选择项目管理员',
    }
  ],
  location2: [
    {
      required: true,
      // message: '请选择项所在地区',
      validator: async (_rule, value) => {
        if (!location2.value) {
          return Promise.reject('请选择项目所在地区');
        } else {
          return Promise.resolve();
        }
      },
    }
  ],
  projectTime: [
    {
      required: true,
      // message: '请选择项目周期',
      validator: async (_rule, value) => {
        if (!projectTime.value) {
          return Promise.reject('请选择项目周期');
        } else {
          return Promise.resolve();
        }
      }
    }
  ],
  state: [
    {
      required: true,
      message: '请选择项目状态',
    }
  ],
  demandContent: [
    {
      required: true,
      message: '请输入项目需求',
    }
  ]
})

function convertDateToCustomObject(inputDate) {
  const customDateObj = {
    $D: inputDate.getDate(),
    $H: inputDate.getHours(),
    $L: "zh-cn",
    $M: inputDate.getMonth() + 1,
    $W: inputDate.getDay(),
    $d: inputDate.toString(),
    $m: inputDate.getMinutes(),
    $ms: inputDate.getMilliseconds(),
    $s: inputDate.getSeconds(),
    $u: undefined,
    $x: "Proxy(Object) {}",
    $y: inputDate.getFullYear()
  };

  return customDateObj;
}

const { resetFields, validate } = useForm(formState, rulesRef);

function projectNameChange() {
  if (formState.projectName == '') {
    errorMessage.value = true
  } else {
    errorMessage.value = false
  }
}

let adminOptions = ref()

async function greatProject() {

  console.log('66699')
  if (location2.value) {
    formState.provinceCode = location2.value[0]
    formState.cityCode = location2.value[1]
  }

  // formState.adminList =  formState.adminList.join(',')
  // formState.memberList = formState.memberList.join(',')
  let { adminList, provinceCode, cityCode, customerName, memberList, startDate, endDate, state, budget, demandContent, otherInfo, projectName, location, customerType } = formState
  if (formState.projectName == '') {
    errorMessage.value = true
  }
  await formRef.value.validate()
  if (formState.projectName == '') {
    errorMessage.value = true
    return
  }
  if (props.edit) {
    const res2 = await editAPi({
      id: props.queryId,
      adminList: adminList.join(','),
      memberList: memberList.join(','),
      provinceCode,
      cityCode,
      customerName,
      budget,
      demandContent,
      otherInfo,
      projectName,
      startDate,
      endDate,
      state,
      location,
      customerType,
      longitude: form.lng,
      latitude: form.lat
    })
  } else {
    const res = await add({
      adminList: adminList.join(','),
      memberList: memberList.join(','),
      provinceCode,
      cityCode,
      customerName,
      budget,
      demandContent,
      otherInfo,
      projectName,
      startDate,
      endDate,
      state,
      location,
      customerType,
      longitude: form.lng,
      latitude: form.lat
    })
  }
  reset()
  visible.value = false
  emit('saveSuccess')
}

function reset() {
  formRef.value.resetFields()
  errorMessage.value = false
  location2.value = ''
  projectTime.value = ''
  form.lng = ''
  form.lat = ''
  form.address = ''
  formState.projectName = ''
  formState.customerName = ''
  formState.customerType = null
  formState.memberList = []
  formState.budget = null
  formState.otherInfo = ''
}

function afterClose() {
  emit('close')
  reset()
}

function stateVal(e) {
  const arr = e[0].map(item => item.label).join('/')
  formState.location = arr
  console.log(arr, 'e')
}

function projectTimeChange(e) {
  console.log(e, 'e')
  const data1 = new Date(e[0].$d)
  const data2 = new Date(e[1].$d)
  formState.startDate = formatDate(data1);
  formState.endDate = formatDate(data2);
  console.log(formState.startDate, formState.endDate)
  const tiem = new Date(e[0])
  console.log(tiem, 'tiem')
}

function adminChange() {
  const array = [...formState.adminList, ...formState.memberList]
  formState.memberList = [...new Set(array)]
}

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  // const hours = date.getHours().toString().padStart(2, '0');
  // const minutes = date.getMinutes().toString().padStart(2, '0');
  // const seconds = date.getSeconds().toString().padStart(2, '0');
  // ${hours}:${minutes}:${seconds}
  return `${year}-${month}-${day} `;
}

function deselect(e) {
  if (formState.adminList.includes(e)) {
    formState.memberList.push(e)
  }
}

onMounted(async () => {
  const res = await UserList()
  adminOptions.value = res.records
  console.log(adminOptions.value, 'adminOptions.value')

})
</script>
<style lang="less" scoped>
/deep/ .ant-form-item-label>label.ant-form-item-required:not(.ant-form-item-required-mark-optional)::before {
  display: none;
}

/deep/ .ant-form-item-label>label.ant-form-item-required:not(.ant-form-item-required-mark-optional)::after {
  display: inline-block;
  margin-right: 4px;
  color: #ff4d4f;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}

#container {
  width: 447px;
  height: 229px
}

.Mapbut {
  position: absolute;
  right: 7px;
  bottom: 7px;
}


.mapLocalBox {
  position: relative;

  .inpBox {
    width: 253px;
    height: 32px;
    // border: 1px solid #d9d9d9;
    // border-radius: 2px;
  }

  .MapBox {
    position: absolute;
    padding: 7px;
    z-index: 100;
    background-color: #FFFFFF;
    box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.09);
    border-radius: 4px;

    .mapSelectBox {
      width: 246px;
      position: absolute;
      top: 11px;
      left: 13px;
      z-index: 1;
      box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.09);
    }
  }
}


.ModalBox {
  background-color: #ebeff4;
  padding: 14px;

  .newProject {
    background-color: #fcfdff;
    border-radius: 2px;
    box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.09);

    .headBox {
      padding: 12px 0px;
      // border-bottom: 1px solid #f0f1f2;
      border-bottom: 1px solid rgba(204, 204, 204, 0.5);

      .inputBox {
        width: 181px;
        height: 40px;
        margin: 0 auto;

        .inputA {
          height: 100%;
          text-align: center;
          border-radius: 20px;
          border: 2px solid #c1d3de;
        }


        .errorMessage {
          color: #ed6f6f;
          text-align: center;
        }
      }
    }

    .infoBox {
      padding: 0 19px;

      .head {
        margin: 0 auto;
        margin-top: 19px;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 111px;
        height: 22px;
        background: rgba(212, 232, 255, 0.44);
        border-radius: 11px;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #2275D3;
        margin-bottom: 20px;
      }

      .basicInform {
        .regionSelect {}

        .addItInform {
          margin: 0 auto;
          margin-top: 19px;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 111px;
          height: 22px;
          background: rgba(255, 247, 232, 0.44);
          border-radius: 11px;
          font-size: 16px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #D39722;
          margin-bottom: 20px;
          // margin-top: 32px;
        }
      }
    }

    .davidLine {
      height: 1px;
      border: 1px solid rgba(204, 204, 204, 0.5);
      margin-top: 54px;
    }

    .footer {
      background-color: #FFFFFF;
      height: 72px;
      display: flex;
      align-items: center;
      justify-content: center;

      .resetBox {
        width: 88px;
        height: 32px;
        border-radius: 2px;
        border: 1px solid #CCCCCC;
        margin-right: 20px;
        font-weight: 400;
        color: #666666;
      }

      .greatProjectBox {
        width: 88px;
        height: 32px;
        background: linear-gradient(315deg, #2C9AD6 0%, #167DB5 100%);
        // box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.16);
        border-radius: 2px;
        font-weight: 400;
        color: #FFFFFF;
        font-size: 14px;
      }
    }
  }
}
</style>
